package com.hc.controller;

import com.hc.bean.Result;
import com.hc.bean.ResultUtil;
import com.hc.domain.User;
import com.hc.service.UserService;
import com.hc.utils.GlobalConstant;
import com.hc.utils.MapUtil;
import com.hc.utils.RedisUtil;
import com.hc.utils.VerifyCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.security.Principal;
import java.util.Map;
import java.util.UUID;

@Api(value = "用户控制器", tags = "用户 User 控制器")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private RedisUtil redisUtil;

    @ApiOperation(value = "getVerifyCode：获取验证码", notes = "获取验证码", httpMethod = "GET")
    @RequestMapping("/v1/getVerifyCode")
    public Result getVerifyCode() {
        String key = UUID.randomUUID().toString();

        //生成验证码，5位
        String code = VerifyCodeUtil.generateVerifyCode(5);
        //生成验证码对应的图片
        String base64Img = null;
        try {
            base64Img = VerifyCodeUtil.outputImage(100, 40, code);
        } catch (IOException e) {
            e.printStackTrace();
            return ResultUtil.fail(200,"验证码生成失败");
        }

        //将生成的数据保存在Redis中
        redisUtil.hset(GlobalConstant.VERIFYCODE_KEY, key, code);
        return ResultUtil.success(200, Map.of("key", key, "code", code, "img", base64Img));
    }

    @Resource
    private UserService userService;

    @ApiOperation(value = "getSysUser：获取用户信息", notes = "获取用户信息，在后台框架页面右侧顶部显示", httpMethod = "GET")
    @GetMapping("/v1/sys/user")
    public Result getSysUser(Principal principal){
        User user = userService.getUserByUsername(principal.getName());
        return ResultUtil.success(200, MapUtil.builder()
                .put("id",user.getId())
                .put("nickname",user.getNickname())
                .put("avatar",user.getAvatar())
                .build());
    }

    /**
     * 查询指定id的用户的所有信息
     *
     * @param id 用户id
     * @return 用户信息
     */
    @GetMapping("/getUserById")
    public User getUserById(Integer id) {
        User user = userService.getById(id);
        return user;
    }






    //@PostMapping("/save")
    //public User save(User user) {
    //    System.out.println("save");
    //    System.out.println(user);
    //    return new User();
    //}
    //


}
